/*
 * VHNavCountryTree.java
 * Created on 14 juin 2009
 *
 * VirtualHockey Internet Platform
 * http://code.google.com/p/virtualhockey/
 *
 * Copyright (c) 2005-2009, Jens and Jan Janke (VirtualHockey Project)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

package com.hockeo.vhweb.client.ui.widget;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.data.BaseTreeLoader;
import com.extjs.gxt.ui.client.data.ModelIconProvider;
import com.extjs.gxt.ui.client.data.ModelStringProvider;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.data.TreeLoader;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanelView;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.TreeNode;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.hockeo.vhweb.client.VHMain;
import com.hockeo.vhweb.client.VHMainController;
import com.hockeo.vhweb.client.mvc.VHController;
import com.hockeo.vhweb.client.mvc.VHView;
import com.hockeo.vhweb.client.res.VHResConstants;
import com.hockeo.vhweb.client.ui.panels.VHPanelAssociation;
import com.hockeo.vhweb.client.ui.panels.VHPanelClub;
import com.hockeo.vhweb.client.utils.VHJsData;
import com.hockeo.vhweb.client.utils.VHJsSimpleData;
import com.hockeo.vhweb.client.utils.VHJsSimpleData.ChildType;

/**
 * Country navigation tree.
 *
 * @version $Id$
 * @author janjanke
 */
public class VHNavCountryTree extends LayoutContainer
{
  private VHView              d_view;
  private TreePanel<VHJsData> d_tree;

  /**
   * Creates a new country navigation tree.
   *
   * @param view the parent view
   */
  public VHNavCountryTree( VHView view )
  {
    d_view = view;
  }

  @Override
  protected void onRender( Element parent, int index )
  {
    super.onRender( parent, index );
    setLayout( new FitLayout() );

    final String strLocale = LocaleInfo.getCurrentLocale().getLocaleName();
    final VHResConstants consts = VHMain.getConstants();

    // data proxy
    //
    RpcProxy<List<VHJsData>> proxy = new RpcProxy<List<VHJsData>>() {
      @Override
      protected void load( Object objParent, AsyncCallback<List<VHJsData>> callback )
      {
        VHJsData model = (VHJsData) objParent;

        if ( model == null )
        {
          // 1st level: countries
          //
          VHController.getBaseDataService().getCountries( strLocale, callback );
        }
        else if ( model.getType().equals( "GNationalAssociation" ) )
        {
          // 2nd level: stats/leagues/cup
          //
          List<VHJsData> list = new ArrayList<VHJsData>();
          VHJsSimpleData data;

          data = new VHJsSimpleData( "stats", consts.navCountryNewsAndStats(), VHMain.ICON_NEWS_AND_STATS );
          data.setParentId( model.getId() );
          data.set( "name", model.getString( "id_translated" ) );
          list.add( data );

          data = new VHJsSimpleData( "leagues", consts.navCountryLeagues(), VHMain.ICON_LEAGUE );
          data.setChildType( ChildType.REMOTE );
          data.setParentId( model.getId() );
          list.add( data );

          data = new VHJsSimpleData( model.getString( "nationalCupId" ), model.getString( "nationalCupId_translated" ),
              VHMain.ICON_NATIONAL_CUP );
          data.setParentId( model.getId() );
          data.set( "menuType", "cup" );
          list.add( data );

          callback.onSuccess( list );
          layout();
        }
        else if ( model.getType().equals( "GLeague" ) )
        {
          // 4th level: load all clubs of the league
          //
          VHController.getBaseDataService().getClubsForLeague( strLocale, model.getId(), callback );
        }
        else if ( model instanceof VHJsSimpleData )
        {
          VHJsSimpleData data = (VHJsSimpleData) model;

          // 3rd level: leagues
          //
          if ( data.getChildType() == ChildType.REMOTE && data.getId().equals( "leagues" ) )
            VHController.getBaseDataService().getLeagues( strLocale, data.getParentId(), callback );
        }
      }
    };

    // tree loader
    //
    TreeLoader<VHJsData> loader = new BaseTreeLoader<VHJsData>( proxy ) {
      @Override
      public boolean hasChildren( VHJsData data )
      {
        return data == null || data.getType().equals( "GNationalAssociation" ) || data.getType().equals( "GLeague" )
            || ( data instanceof VHJsSimpleData && ( (VHJsSimpleData) data ).getChildType() != ChildType.NONE );
      }
    };

    // trees store
    //
    TreeStore<VHJsData> store = new TreeStore<VHJsData>( loader );

    // tree panel
    //
    d_tree = new TreePanel<VHJsData>( store ) {
      /**
       * Overridden to avoid opening league nodes via double click.
       */
      @SuppressWarnings( "unchecked" )
      @Override
      protected void onDoubleClick( TreePanelEvent evt )
      {
        VHJsData data = (VHJsData) evt.getNode().getModel();

        if ( data.getType() != null && data.getType().equals( "GLeague" ) )
          return;

        super.onDoubleClick( evt );
      }
    };

    // tree view
    //
    d_tree.setView( new TreePanelView<VHJsData>() {
      /**
       * Overridden to avoid that the wait icon is not shown for nodes that are not loaded
       * from the server.
       */
      @SuppressWarnings( "unchecked" )
      @Override
      public void onLoading( TreeNode node )
      {
        VHJsData data = (VHJsData) node.getModel();

        if ( data.getType() != null && data.getType().equals( "GNationalAssociation" ) )
          return;

        super.onLoading( node );
      }
    } );

    // Labels
    //
    d_tree.setLabelProvider( new ModelStringProvider<VHJsData>() {
      public String getStringValue( VHJsData model, String property )
      {
        if ( model.getType().equals( "GClub" ) )
          return model.getString( "name" );
        else if ( model.isRemote() )
          return model.getString( "id_translated" );
        else if ( model instanceof VHJsSimpleData )
          return ( (VHJsSimpleData) model ).getLabel();

        return "TODO";
      }
    } );

    // Icons
    //
    d_tree.setIconProvider( new ModelIconProvider<VHJsData>() {
      public AbstractImagePrototype getIcon( VHJsData model )
      {
        if ( model.getType().equals( "GNationalAssociation" ) )
          return IconHelper.create( "images/flags/16x16/" + model.getId() + ".png", 16, 16 );
        else if ( model.getType().equals( "GLeague" ) )
          return VHMain.ICON_LEAGUE;
        else if ( model.getType().equals( "GClub" ) )
          return VHMain.ICON_CLUB;
        else if ( model instanceof VHJsSimpleData )
          return ( (VHJsSimpleData) model ).getIcon();

        return null;
      }
    } );

    // React to double-click events
    //
    d_tree.addListener( Events.OnDoubleClick, new Listener<TreePanelEvent<VHJsData>>() {
      @SuppressWarnings( "synthetic-access" )
      public void handleEvent( TreePanelEvent<VHJsData> evt )
      {
        VHJsData data = (VHJsData) evt.getNode().getModel();

        if ( data.getType().equals( "GLeague" ) )
          ( (VHMainController) d_view.getController() ).displayLeague( data );
        else if ( data.getType().equals( "GClub" ) )
          ( (VHMainController) d_view.getController() ).displayPanel( VHPanelClub.get( d_view.getController(),
              data.getId() ), VHMain.getMessages().clubPanelHeader( data.getString( "name" ) ), VHMain.ICON_CLUB );
        else if ( data.getString( "menuType" ) != null && data.getString( "menuType" ).equals( "cup" ) )
          ( (VHMainController) d_view.getController() ).displayCup( data.getId(),
              data.getString( VHJsSimpleData.PARAM_LABEL ) );
        else if ( data.getId().equals( "stats" ) )
          ( (VHMainController) d_view.getController() ).displayPanel( VHPanelAssociation.get( d_view.getController(),
              ((VHJsSimpleData) data).getParentId() ), VHMain.getMessages().assocPanelHeader( data.getString( "name" ) ), VHMain.ICON_CLUB );
        else
          Window.alert( "Node '" + data.getId() + "' not (yet) handled." );
      }
    } );

    add( d_tree );
  }
}
